import { List, SideBar } from "antd-mobile";
import { useMemo, useState } from "react";
// 复用城市列表的两栏样式
import styles from '../Cityslice/index.module.css'

type OfficeItem = {
  adminname: string
  adminchildrenname: string
  [key: string]: unknown
}

interface Props {
  data?: OfficeItem[]
  onSelect?: (dept: string) => void
}

function Index({ data = [], onSelect }: Props) {
  const [activeKey, setActiveKey] = useState("0");

  // 左侧唯一 adminname 列表
  const adminList = useMemo(() => {
    const set = new Set<string>();
    const list: string[] = [];
    for (const item of data) {
      if (!set.has(item.adminname)) {
        set.add(item.adminname);
        list.push(item.adminname);
      }
    }
    return list;
  }, [data]);

  // 右侧映射：adminname -> 该类下的子科室列表
  const childrenMap = useMemo(() => {
    const map = new Map<string, string[]>();
    for (const name of adminList) map.set(name, []);
    for (const item of data) {
      const arr = map.get(item.adminname);
      if (!arr) continue;
      arr.push(item.adminchildrenname);
    }
    return map;
  }, [data, adminList]);

  const currentAdmin = adminList[Number(activeKey)] || '';
  const currentChildren = childrenMap.get(currentAdmin) || [];

  return (
    <div className={styles.container}>
      <div className={styles.inner}>
        <SideBar className={styles.left} style={{width:150}} activeKey={activeKey} onChange={setActiveKey}>
          {adminList.map((name, index) => (
            <SideBar.Item key={String(index)} title={name} />
          ))}
        </SideBar>

        <div className={styles.right} style={{flex:1, paddingLeft:12}}>
          <List>
            {currentChildren.map((child, idx) => (
              <List.Item
                arrowIcon={false}
                key={`${currentAdmin}-${child}-${idx}`}
                style={{
                  fontSize: 'var(--adm-font-size-main)',
                  color: 'var(--adm-color-text)'
                }}
                onClick={() => onSelect?.(child)}
              >
                {child}
              </List.Item>
            ))}
          </List>
        </div>
      </div>
    </div>
  )
}

export default Index
